<?php

namespace plugin\voice\app\admin\controller;

use support\Request;
use Webman\Medoo\Medoo as db;

class ChatController{

    public function index(Request $request){
        return raw_view('chat/index');
    }

    public function insert(Request $request){
        if ($request->method() === 'POST') {
            db::insert('voice_chat', $request->post());
            return json([
                'code' => 0,
                'msg'  => 'ok'
            ]);
        }
        return raw_view('chat/insert');
    }
    
    public function select(Request $request){
        $condition = []; // 初始化条件数组
        foreach ($request->get() as $key => $value) {
            if($value && !in_array($key,['page','limit'])){
                $condition = array_merge($condition, [$key => $value]); // 将条件合并到数组中
            }
        }
        $countTotal = db::count('voice_chat',$condition);
        $condition  = array_merge($condition, ['LIMIT' => [($request->get('page')-1)*$request->get('limit'),$request->get('limit')],'ORDER' => ['ID' => 'DESC']]);
        $chats      = db::select('voice_chat','*',$condition);
        $contentType = ['','文本','语音','图片','文件'];
        foreach ($chats as &$chat) {
            $chat['content_type_name'] = $contentType[$chat['content_type']];
            $chat['role_name']         = db::get('voice_roles','name',['id' => $chat['role_id']]);
            $chat['user_name']         = db::get('voice_users','username',['id' => $chat['user_id']]);
        }
        return json([
            'code'  => 0, 
            'msg'   => 'ok', 
            'count' => $countTotal,
            'data'  => $chats
        ]);
    }

    public function update(Request $request){
        if ($request->method() === 'POST') {
            $postData = $request->post();
            if(isset($postData['password']) && $postData['password']==''){
                unset($postData['password']);
            }
            db::update('voice_chat',$postData,['id' => $postData['id']]);
            return json([
                'code' => 0,
                'msg'  => 'ok'
            ]);
        }
        return raw_view('chat/update');
    }
    
    public function delete(Request $request){
        db::delete('voice_chat',['id' => $request->post('id')]);
        return json([
            'code' => 0,
            'msg'  => '删除成功'
        ]);
    }

}
